package com.tlsy.commerce.shiro;

import com.tlsy.commerce.model.Role;
import com.tlsy.commerce.model.User;
import com.tlsy.commerce.model_enum.StatusEnum;
import com.tlsy.commerce.service.SystemService;
import com.tlsy.commerce.utils.AppConfig;
import com.tlsy.commerce.utils.ShiroUtil;
import com.tlsy.commerce.utils.StringUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Tlsy
 * @version commerce 0.0.1
 * @date 2017/4/20  11:00
 */
public class NormalRealm extends AuthorizingRealm {

    @Autowired
    private SystemService systemService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        User user= (User) ShiroUtil.getSubject().getSession().getAttribute(AppConfig.USER_SESSION);

        if(user != null){
            Set<String> roles = new HashSet<String>();
  //          Set<String> resources = new HashSet<String>();
            List<Role> rList = user.getRoles();
            for (Role role : rList) {
                roles.add(role.getCode());
                //todo 暂时没有权限资源
//               List<Resource> res = role.getResources();
//                for (Resource resource : res) {
//                    resources.add(resource.getResourceCode());
//                }
            }
            //将角色编码放入shiro中
            simpleAuthorizationInfo.setRoles(roles);
            //将资源编码放入shiro中
         //   simpleAuthorizationInfo.setStringPermissions(resources);
        }

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomUsernamePasswordToken usernamePasswordToken=(CustomUsernamePasswordToken) authenticationToken;
        String phone=usernamePasswordToken.getUsername();

        User user=systemService.findUserByPhone(phone);

        if(user == null){
            throw new AuthenticationException("用户"+phone+"不存在");
        }

        if(user.getStatus()== StatusEnum.DISABLED){
            throw new AuthenticationException("用户:"+user.getName()+"已被禁用");
        }

        //todo 验证码
        byte[] salt = StringUtil.decodeHex(user.getPassword().substring(0,16));

        return new SimpleAuthenticationInfo(new CustomPrincipal(user,usernamePasswordToken.isMobileLogin()),user.getPassword().substring(16), ByteSource.Util.bytes(salt),getName());
    }
}
